import { ref } from "vue";
import { useRoute } from "vue-router";
import { getDetailAPI } from "@/api/detail.js";
import { useCartStore } from "@/stores/cart.js";
import { ElMessage } from "element-plus";
import router from "@/router/index.js";


export const useDetail = () => {

  const detail = ref({})
  const isLoading = ref(false);

  const goods = ref({
    skus: detail.value.skus,
    specs: detail.value.specs,
  })
  const skuObj = ref({})

  const route = useRoute()
  const getDetail = async (id=route.params.id) => {
    isLoading.value = true
    const res = await getDetailAPI(id)
    detail.value = res.result
    isLoading.value = false
    goods.value.skus = detail.value.skus
    goods.value.specs = detail.value.specs
  }

  const count = ref(0)
  const cartStore = useCartStore()

  const handleChange = () => {
    skuObj.value.count = count.value
    skuObj.value.name = detail.value.name
    skuObj.value.picture = detail.value.details.pictures[0]
    skuObj.value.id = detail.value.id
    skuObj.value.selected = true
    skuObj.value.attrsText = skuObj.value.specsText
  }

  const addCart = () => {
    console.log(skuObj.value)
    if (!skuObj.value.count) {
      ElMessage.warning('商品数不小于1')
      return
    }
    if (!skuObj.value.skuId) {
      ElMessage.warning('请添加规格')
    } else {
      cartStore.addToCart(skuObj.value)
      ElMessage.success('添加成功')
      router.push('/cart')
    }
  }

  return {
    detail,
    isLoading,
    goods,
    skuObj,
    getDetail,
    handleChange,
    addCart,
    count
  }

}
